<script lang="ts" setup>
import { ElButton, ElTableColumn, FormRules, ElTable, ElDialog, FormInstance, ElForm, ElFormItem, ElInput, UploadProps, UploadFile, TabsPaneContext, ElMessage, ElImage } from "element-plus"
import Header from "@/views/content/util/header.vue"
import { onMounted, ref, reactive,defineEmits, defineProps } from "vue"
import {getStaffInfoApi, getStaffGroupNameListApi, isFaceApi } from '@/apis/staffApi'
import { staff } from '@/pojo/dto/staff'
import { res } from '@/pojo/dto/res'
import SButton from "@/views/content/util/button/sButton.vue"
const props = defineProps({
    staffId: {
        type: Number,
        default: () => null
    },
    title: {
        type: String,
        default: () => null
    }
})
//员工编辑
const editStaff = ref({
    sort: 1,
    face: [],
    id: 0,
    name: '',
    groupName: '',
    phone: '',
    sex: '',
    password: '',
    status: 0
})
const showPop = ref(true)
const ruleFormRef = ref<FormInstance>()
//校验规则
const rules = reactive<FormRules>({
    name: [
        { required: true, message: "请输入员工姓名", trigger: "blur" },
        { min: 1, max: 30, message: "员工名称长度不得超过30", trigger: "blur" },
    ],
    groupName: [
        {
            required: true,
            message: "请选择角色",
            trigger: "change",
        },
    ],
    phone: [
        {
            required: true,
            message: "请填写登录账号",
            trigger: "change",
        },
    ],
    password: [
        {
            required: true,
            message: "请填写登录密码",
            trigger: "change",
        },
    ],
});
//---------------------------------------------------------------------------------图片相关-------------------------------------------------------------
const noUpload = ref(false)//不再上传
const isFace = (faceFile:File) => {
    return new Promise((resolve) => {
        const reader = new FileReader()
        reader.onload = async () => {
            const faceBase64 = reader.result.split(",")[1]
            const res: res = await isFaceApi(faceBase64)
            if (res.code === 0) {
                resolve(true)
            } else {
                resolve(false)
            }
        }
        reader.readAsDataURL(faceFile)
    })
}



const validImageFormats = ["jpg", "jpeg", "png"];//允许的文件后缀
//选择文件格式校验//并限制上传数量/并校验是否为人脸
const checkImageFormat = async (file:UploadFile) => {
    console.log("文件格式校验")
    console.log(file)
    // noUpload.value = true
    //后缀校验
    const fileFormat = file.name.split(".").pop().toLowerCase() // 获取文件格式
    if (!validImageFormats.includes(fileFormat)) {
        ElMessage({ type: "error", message: "员工人脸格式必须为 jpg/jpeg/png" })
        editStaff.value.face = [] //删除格式不符合的文件
        return false
    }
    noUpload.value = true//阻止继续上传
    //人脸校验
    const isFaceValid = await isFace(file.raw)
    if (!isFaceValid) {
        ElMessage({
            type: 'error',
            message: '人脸校验不通过，请重试！',
            showClose: true

        })
        editStaff.value.face = []; //删除格式不符合的文件
        noUpload.value = false
        return false;
    }
    ElMessage({
        type: 'success',
        message: '人脸校验通过',
        showClose: true
    })


    return true; // 允许文件上传
};


const dialogImageUrl = ref(""); //预览图片路径
const dialogVisible = ref(false); //预览框可见
//删除
const handleRemove: UploadProps["onRemove"] = (file: UploadFile) => {
    noUpload.value = false
};

//预览
const handlePictureCardPreview: UploadProps["onPreview"] = (file: UploadFile) => {
    dialogImageUrl.value = file.url!;
    dialogVisible.value = true;
};

//--------------------------------------------------------------------------------------员工编辑----------------------------------------------------------------------------------------
// onBeforeMount(() => {
//     if(props.staffId){
//         getEcho(props.staffId)
//     }
// })

const getEcho = async (echoStaffId: Number) => {
    const res: res = await getStaffInfoApi(echoStaffId)
    if (res.code === 0) {
        editStaff.value.sort = res.data.sort
        editStaff.value.name = res.data.name
        editStaff.value.phone = res.data.phone
        editStaff.value.password = res.data.password
        editStaff.value.groupName = res.data.groupName
    }
    else {
        ElMessage({ type: 'error', message: res.message })
    }
}
//置空
const doEmpt = () => {
    editStaff.value.sort = 1,
        editStaff.value.face = [],
        editStaff.value.id = 0,
        editStaff.value.name = '',
        editStaff.value.groupName = '',
        editStaff.value.phone = '',
        editStaff.value.sex = '',
        editStaff.value.password = '',
        editStaff.value.status = 0

}

//关闭事件
const emit = defineEmits(["exitEditPage"]);
function goBack() {
    emit("exitEditPage");
}

//提交表单(编辑员工)
const submitFormEdit = async (formEl: FormInstance | undefined) => {
    // console.log(editStaff);
    console.log('提交编辑表单');
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
        if (valid) {
        } else {
            ElMessage({ type: "error", message: "请正确填写必要信息！" });
        }

    })
}

//提交表单(添加员工)
const submitFormAdd = async (formEl: FormInstance | undefined) => {
    // console.log(editStaff);
    console.log('提交添加表单');
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
        if (valid) {
        } else {
            ElMessage({ type: "error", message: "请正确填写必要信息！" });
        }

    })
}
//--------------------------------------------------------------------------------添加员工-----------------------------------------------------------------------------------------
const staffGroupNames = ref([])
onMounted(() => {
    if (props.staffId) {
        //回显函数
        getEcho(props.staffId)
    }
})
</script>
<template>
    <div>
        <el-dialog :model="true" v-model="showPop" :title="props.title" :before-close="() => { goBack() }" draggable
            :show-close="true" style="border-radius: 10px;">
            <el-form ref="ruleFormRef" :model="editStaff" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="人脸照片" prop="face">
                            <el-upload :class="{ disabled: noUpload }" :auto-upload="false" list-type="picture-card"
                                :on-preview="handlePictureCardPreview" :on-change="checkImageFormat"
                                :on-remove="handleRemove" :limit="1" ref="businessLicense" :file-list="editStaff.face">
                                <el-icon v-if="editStaff.face.length == 0">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                            <label style="
                    color: rgb(243, 183, 106);
                  ">提示：请上传员工真实人脸照片</label>
                            <el-dialog v-model="dialogVisible">
                                <img w-full :src="dialogImageUrl" alt="Preview Image" />
                            </el-dialog>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item :label="'排序'" prop="sort">
                            <el-input-number v-model="editStaff.sort" style="width: 200px;" min
                                precision="0"></el-input-number>
                        </el-form-item>
                        <el-form-item :label="'姓名'" prop="name">
                            <el-input v-model="editStaff.name" style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item :label="'用户组'" prop="groupName">
                            <el-select v-model="editStaff.groupName" placeholder="请选择角色">
                                <el-option :label="'管理员'" :value="'管理员'" />
                                <el-option v-for="item in staffGroupNames" :label=item.name :value=item.name />
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="'登录账号'" prop="phone">
                            <el-input v-model="editStaff.phone" style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item :label="'登录密码'" prop="password">
                            <el-input v-model="editStaff.password" type="password" show-password
                                style="width: 300px;"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span style="position: relative;top: 10px;left: 80%;">
                <SButton @click="goBack()" title="取消" type="cancel"/>
                <SButton type="save" title="保存"
                    @click="props.staffId ? submitFormEdit(ruleFormRef) : submitFormAdd(ruleFormRef)"/>
            </span>
        </el-dialog>
    </div>
</template>
<style lang="scss" scoped></style>